//导入路由
import router from './router'
//导入vuex中的token
import store from '@/store'
//导入message提示信息
import { Message } from 'element-ui'

//配置路由导航守卫
router.beforeEach(async (to, from, next) => {
  const token = store.getters.token
  const white = ['/login', '/404']
  //判断是否有token
  if (token) {
    //判断是否有用户信息
    if (!store.getters.userInfo.username) {
      const userInfo = await store.dispatch('user/getInfo')
      // console.log(userInfo);
      const myroutes = await store.dispatch(
        'permissions/set_routes',
        userInfo.roles.menus
      )
      console.log(myroutes);
      router.addRoutes([
        ...myroutes,
        // 404 page must be placed at the end !!!
        { path: '*', redirect: '/404', hidden: true }
      ])
      next(to.path)
    }
    //判断是否为登录页面，是则跳转到首页，否则直接执行
    if (to.path === '/login') {
      // Message.info('您已登录，请勿重复操作')
      Message({
        duration: 1000,
        message: '您已登录，请勿重复操作',
        type: 'info'
      })
      next('/')
    } else {
      next()
    }
  } else {
    //没有token则判断是否是白名单,是则直接执行，否则跳转到登录页
    if (white.indexOf(to.path) != -1) {
      next()
    } else {
      // Message.info('您未登录，请登录')
      Message({
        duration: 1000,
        message: '您未登录，请登录',
        type: 'info'
      })
      next(`/login?_redirect=${to.path}`)
    }
  }
})
